#include "thread.h"
#include "threadpool.h"

// 线程执行任务的入口函数
void* doTask(void *task_arg)
{
    ThreadPool *pool = (ThreadPool*)task_arg;
	
    for (;;)
    {
        // 先获取锁
        pthread_mutex_lock(&pool->queMutex_);
        // 如果任务队列位空，等待条件变量成立
        while (pool->taskQue_.size() == 0)
        {
            pthread_cond_wait(&pool->queCond_, &pool->queMutex_);
        }

        // 从队列中取出一个任务 wp
        shared_ptr<Task> sp = pool->taskQue_.front();
        pool->taskQue_.pop();
        pthread_mutex_unlock(&pool->queMutex_);

        sp->run(); 
    }
}

Thread::Thread(ThreadPool *pool)
    : pool_(pool)
{}

// 开始执行
void Thread::start()
{
    pthread_create(&tid_, NULL, doTask, pool_);
}